<script lang="tsx" setup>
import { NButton, NPopconfirm } from 'naive-ui';
import { toRefs } from 'vue';
import { delPackage, getPageList } from '@/service/api/tenants/package';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { useDict } from '@/utils/dict';
import DictTag from '@/components/custom/dict-tag.vue';
import SvgIcon from '@/components/custom/svg-icon.vue';
import type { PackageVO } from '@/service/types/tenant';
import PackageSearch from './components/package-search.vue';
import PackageForm from './components/package-form.vue';
const { sys_normal_disable } = toRefs<any>(useDict('sys_normal_disable'));
const appStore = useAppStore();
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: getPageList,
  showTotal: true,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    packageName: ''
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'packageName',
      title: '套餐名称',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'remark',
      title: '备注',
      align: 'left',
      minWidth: 100,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      minWidth: 100,
      render: row => {
        return <DictTag type="badge" value={row.status} dicts={sys_normal_disable.value} />;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 130,
      render: (row: PackageVO) => (
        <div class="flex-center gap-15px">
          <NButton
            tag="a"
            type="primary"
            text
            size="small"
            onClick={() => {
              editor(row?.packageId);
            }}
          >
            {{
              icon: () => <SvgIcon icon="ant-design:edit-outlined" />
            }}
          </NButton>
          <NPopconfirm
            onPositiveClick={() => {
              handleDelete(row.packageId as number);
            }}
            onNegativeClick={() => {
              (window as any).$message.info('已取消删除');
            }}
          >
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton text tag="a" type="error" ghost size="small">
                  {{
                    icon: () => <SvgIcon icon="ant-design:delete-outlined" />
                  }}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});
const {
  drawerVisible,
  operateType,
  handleAdd,
  checkedRowKeys,
  customerEdit,
  currentId,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);
const editor = (id: number | string) => {
  customerEdit(id);
};
const handleDelete = async (id: number) => {
  const result = await requestRemove(id as number);
  if (result) {
    onDeleted();
  }
};
const requestRemove = async (id: number | number[]): Promise<boolean> => {
  const loadinginstance = (window as any).$message.loading('正在处理中');
  const { data, error } = await delPackage(id as number);
  loadinginstance.destroy();
  if (!error) {
    (window as any).$message.success(data?.msg);
    return Promise.resolve(true);
  }
  throw new Error('false');
};
const handleBatchDelete = async () => {
  (window as any).$dialog.warning({
    title: '警告',
    content: '你确定删除这些吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const result = await requestRemove(checkedRowKeys.value as unknown as number[]);
      if (result) {
        onBatchDeleted();
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('删除已取消');
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <PackageSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <NCard title="套餐列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getData"
          @delete="handleBatchDelete"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      >
        <template #empty>
          <Empty />
        </template>
      </NDataTable>
    </NCard>
    <PackageForm
      v-model:visible="drawerVisible"
      :current-id="currentId"
      :operate-type="operateType"
      @submitted="getData()"
    />
  </div>
</template>

<style scoped></style>
